package org.tcx.common;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class IOUtil {
	private static final Log log = LogFactory.getLog(IOUtil.class);

	private static void silentlyClose(Closeable closeable) {
		try {
			close(closeable);
		} catch (IOException e) {
			log.debug("IOException", e);
		}
	}

	public static void silentlyClose(Closeable... closeables) {
		for (Closeable closeable : closeables) {
			silentlyClose(closeable);
		}
	}

	public static void close(Closeable closeable) throws IOException {
		if (closeable != null) {
			closeable.close();
		}
	}

	public static void copy(File src, File dst) throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dst);
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} finally {
			silentlyClose(in, out);
		}
	}

	public static void clear(File file, String deletefilepatternStr) {
		if (file.isDirectory()) {
			File[] subfiles = file.listFiles();
			if (subfiles.length == 0) {
				file.delete();
			}
			for (File sub : subfiles) {
				clear(sub, deletefilepatternStr);
			}
		} else if (file.isFile()) {
			if (Pattern.matches(deletefilepatternStr, file.getAbsolutePath())) {
				file.delete();
			}
			File parent = file.getParentFile();
			if (parent != null && parent.listFiles().length == 0) {
				parent.delete();
			}
		}
	}
}
